# encoding=utf-8
import json

from flask import request, jsonify

from app.Service.LogService import LogService
from app.Vendor.Code import Code
from app.Vendor.Log import log
from app.Vendor.NpEncoder import NpEncoder
from app.Vendor.Utils import Utils
from app.env import DEBUG_LOG, SAVE_LOG


class ResultData:

    def json(self, body=None):
        '''
        * 返回Json数据
        * @param  dict body
        * @return json
        '''
        if DEBUG_LOG:
            debug_id = Utils.unique_id()
            data = {
                'LOG_ID': debug_id,
                'IP_ADDRESS': request.remote_addr,
                'REQUEST_URL': request.url,
                'REQUEST_METHOD': request.method,
                'PARAMETERS': request.args,
                'RESPONSES': body
            }
            if SAVE_LOG == 1:
                log().debug(data)
            elif SAVE_LOG == 2:
                LogService().add(json.dumps(data), 1, 2)
            body['debug_id'] = debug_id
        return jsonify(body)

    def error(self, msg=''):
        return self.json({'error_code': Code.BAD_REQUEST, 'error_msg': msg})

    def sucess(self, data='', msg=''):
        return self.json({'error_code': Code.SUCCESS, 'data': data, 'msg': msg})
